from flask import Blueprint, render_template, jsonify, request
from models.entity.district_item import DistrictItem
from models.entity.district import District
import json

mod = Blueprint("core_district_item", __name__, url_prefix="/core/district_item", template_folder="templates",
                static_folder="static")


@mod.route('/add/', methods=['GET', 'POST'])
def add_district_item():
    """新增主分区"""
    """
    {
    "district_id":2,
    "lng":220.888,
    "lat":662.999,
    "dis_order":2
    }
    """
    if request.method == 'POST':
        tmp = {}
        receive = request.data
        dict = json.loads(receive.decode("utf-8"))
        data = []
        dis_order = dict['dis_order']
        district_id = dict['district_id']
        lng = float(dict['lng'])  # 经度
        lat = float(dict['lat'])  # 经度
        if not District.query.filter_by(id=district_id).first():
            tmp['success'] = 0
            tmp['error_code'] = -3
            tmp['error_msg'] = "主分区不存在"
            tmp['data'] = data
            return jsonify(tmp)
        district_item = DistrictItem()

        district_item.district_id = district_id
        district_item.lng = lng
        district_item.lat = lat
        district_item.dis_order = int(dis_order)

        if district_item.save():
            tmp['success'] = 1
            tmp['error_code'] = None
            tmp['error_msg'] = None
            tmp['data'] = data
            return jsonify(tmp)
        else:
            tmp['success'] = 0
            tmp['error_code'] = -3
            tmp['error_msg'] = "unknown Error"
            tmp['data'] = data
            return jsonify(tmp)


@mod.route('/del/', methods=['GET', 'POST'])
def del_district_item():
    """删除点"""
    """
    {
    "id": 1
    }
    """
    if request.method == 'POST':
        receive = request.data
        dict = json.loads(receive.decode("utf-8"))
        id = dict['id']
        data = []
        tmp = {}
        if not DistrictItem.query.filter_by(id=id).first():
            tmp['success'] = 0
            tmp['error_code'] = -2
            tmp['error_msg'] = "数据库中没有该记录"
            tmp['data'] = data
            return jsonify(tmp)
        district_item = DistrictItem.query.filter_by(id=id).first()

        if district_item.delete():
            tmp['success'] = 1
            tmp['error_code'] = None
            tmp['error_msg'] = None
            tmp['data'] = data
            return jsonify(tmp)
        else:
            tmp['success'] = 0
            tmp['error_code'] = -1
            tmp['error_msg'] = "unexcept Error"
            tmp['data'] = data
            return jsonify(tmp)


@mod.route('/get_all/', methods=['GET', 'POST'])
def get_all_district_item():
    """得到全部子区域"""
    district_items = DistrictItem.query.all()
    data = []
    tmp = {}
    for item in district_items:
        data.append({"id": +item.id, "district_id": item.district_id,
                     "lat": item.lat, "lng": item.lng,
                     "dis_order": item.dis_order})
    tmp['success'] = 1
    tmp['error_code'] = None
    tmp['error_msg'] = None
    tmp['data'] = data
    return jsonify(tmp)


@mod.route('/get_all_by_district_id/', methods=['GET', 'POST'])
def get_district_item_by_district():
    """得到一个主区域下的子区域"""
    """
    {
    "id":1
    }
    """
    if request.method == 'POST':
        receive = request.data
        dict = json.loads(receive.decode("utf-8"))
        id = dict['id']
        data = []
        tmp = {}
        district_items = DistrictItem.query.filter_by(district_id=id).order_by('dis_order').all()
        for item in district_items:
            data.append({"id": +item.id, "district_id": item.district_id,
                         "lat": item.lat, "lng": item.lng,
                         "dis_order": item.dis_order})
        tmp['success'] = 1
        tmp['error_code'] = None
        tmp['error_msg'] = None
        tmp['data'] = data
        return jsonify(tmp)


"""
@mod.route('/edit', methods=['GET', 'POST'])
def edit_district_master():
    得到字典列表中的字典项"""


@mod.route('/edit/', methods=['GET', 'POST'])
def edit_point():
    """编辑子区域"""
    """
    {
   
    "id":1,
    
    "district_id":1,

   
    "lng":130,
    "lat":92,
    "dis_order":2
    
    }
    """
    if request.method == 'POST':
        tmp = {}
        receive = request.data
        dict = json.loads(receive.decode("utf-8"))
        data = []
        if "id" not in dict:
            tmp['success'] = 0
            tmp['error_code'] = -1
            tmp['error_msg'] = "主键为空，格式错误"
            tmp['data'] = data
            return jsonify(tmp)
        id = dict['id']

        if "district_id" not in dict:
            tmp['success'] = 0
            tmp['error_code'] = -1
            tmp['error_msg'] = "主分区为空"
            tmp['data'] = data
            return jsonify(tmp)
        district_id = int(dict['district_id'])
        lng = float(dict['lng'])
        lat = float(dict['lat'])

        dis_order = int(dict['dis_order'])

        district_item = DistrictItem.query.filter_by(id=id).first()
        if district_item is None:
            error_msg={
                                            "success":0,
                                            "error_code":-2,
                                            "error_msg":"分区点不存在"
                                }
            return jsonify(error_msg)
        district_item.lng = lng
        district_item.lat = lat
        district_item.district_id = district_id
        district_item.dis_order = dis_order

        if district_item.save():
            tmp['success'] = 1
            tmp['error_code'] = None
            tmp['error_msg'] = None
            tmp['data'] = data
            return jsonify(tmp)
        else:
            tmp['success'] = 0
            tmp['error_code'] = -3
            tmp['error_msg'] = "unknown Error"
            tmp['data'] = data
            return jsonify(tmp)